import { Injectable } from '@nestjs/common';
import { BaseService } from '@nbase/db';
import { sysAuditLog, type NewSysAuditLog, type SysAuditLog } from '@nbase/db';
import { and, gte, ilike, lte, eq, type SQL } from 'drizzle-orm';
import type { IPaginationResponse, IAuditLog } from '@nbase/shared';
import type { QueryAuditLogDto } from './dto/query-audit-log.dto';
import type { IAuditLogService, AuditLogData } from '@nbase/nest-mods';
import { toAuditLogPage } from './audit-log.mapper';

/**
 * 审计日志服务
 */
@Injectable()
export class AuditLogService extends BaseService<typeof sysAuditLog> implements IAuditLogService {
  constructor() {
    super(sysAuditLog);
  }

  /**
   * 创建审计日志（实现 IAuditLogService 接口）
   */
  async createLog(data: AuditLogData | NewSysAuditLog): Promise<void> {
    await this.create(data);
  }

  /**
   * 分页查询审计日志
   */
  async findPage(dto: QueryAuditLogDto): Promise<IPaginationResponse<IAuditLog>> {
    const conditions: SQL[] = [];

    if (dto.username) {
      conditions.push(ilike(this.table.username, `%${dto.username}%`));
    }

    if (dto.module) {
      conditions.push(ilike(this.table.module, `%${dto.module}%`));
    }

    if (dto.operationType) {
      conditions.push(eq(this.table.operationType, dto.operationType));
    }

    if (dto.method) {
      conditions.push(eq(this.table.method, dto.method));
    }

    if (dto.path) {
      conditions.push(ilike(this.table.path, `%${dto.path}%`));
    }

    if (dto.ip) {
      conditions.push(ilike(this.table.ip, `%${dto.ip}%`));
    }

    if (dto.startDate) {
      conditions.push(gte(this.table.createdAt, new Date(dto.startDate)));
    }

    if (dto.endDate) {
      const endDate = new Date(dto.endDate);
      endDate.setHours(23, 59, 59, 999);
      conditions.push(lte(this.table.createdAt, endDate));
    }

    const where = conditions.length > 0 ? and(...conditions) : undefined;

    const result = await this.paginate(
      {
        page: dto.page,
        pageSize: dto.pageSize,
        sortBy: 'createdAt',
        sortOrder: 'desc',
      },
      where
    );

    return toAuditLogPage(result as IPaginationResponse<SysAuditLog>);
  }

  // 审计日志只可插入，不可删除（保证审计记录的完整性）
}

